package com.example.controller;

import com.example.common.Result;
import com.example.entity.CartItem;
import com.example.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/cart")
@Slf4j
public class CartController {
    private final CartService cartService;

    public CartController(CartService cartService) {
        this.cartService = cartService;
    }

    @PostMapping("/add")
    public Result<CartItem> addToCart(@RequestParam("userId") Long userId,
            @RequestParam("productId") Long productId,
            @RequestParam("quantity") Integer quantity) {
        CartItem cartItem = cartService.addToCart(userId, productId, quantity);
        if (cartItem != null) {
            return Result.success(cartItem);
        } else {
            return Result.error("添加购物车失败");
        }
    }

    @GetMapping("/list/{userId}")
    public Result<List<CartItem>> getUserCart(@PathVariable("userId") Long userId) {
        return Result.success(cartService.getUserCart(userId));
    }

    @PostMapping("/checkout/{userId}")
    public Result<Boolean> checkout(@PathVariable("userId") Long userId) {
        boolean success = cartService.checkout(userId);
        if (success) {
            return Result.success(true);
        } else {
            return Result.error("结算失败");
        }
    }

    @GetMapping("/dummyList")
    public Result<List<CartItem>> getDummyCartItemList() {
        List<CartItem> list = new ArrayList<>();
        list.add(new CartItem(1L, 1L, 100L, 2, 1999.0));
        list.add(new CartItem(2L, 1L, 101L, 1, 2999.0));
        list.add(new CartItem(3L, 1L, 102L, 5, 9.9));
        return Result.success(list);
    }
}